package cn.cms.controller;

import cn.cms.constants.Constants;
import cn.cms.util.DateUtil;
import cn.cms.util.Md5Util;
import cn.cms.util.ResponseUtil;
import cn.cms.util.StringUtil;
import cn.cms.webcommon.ResBo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;

@Controller
@RequestMapping(value = "/supload")
public class SuploadController extends AbstractController {

    @RequestMapping(value = "/page")
    public String upload() {
        return "supload/page";
    }

    @RequestMapping("/sfile")
    @ResponseBody
    public void upload(HttpServletResponse response, @RequestParam("file") MultipartFile multipartFile) throws Exception {
        logger.info("上传文件原始名file originalFilename : " + multipartFile.getOriginalFilename());
        ResBo resBo = new ResBo();
        if (multipartFile.isEmpty()) {
            resBo.setSuccess(false);
            resBo.setErrMsg("文件不能为空！");
            logger.warn("文件不能为空！");
            ResponseUtil.printAjax(response, resBo);
            return;
        }
        String fileName = multipartFile.getOriginalFilename();

        if (StringUtil.isSpaceOrNull(fileName)) {
            resBo.setSuccess(false);
            resBo.setErrMsg("文件名不能为空！");
            logger.warn("文件名不能为空！");
            ResponseUtil.printAjax(response, resBo);
            return;
        }

        String downloadDir = "";
        String md5 = "";
        if (fileName.endsWith(".apk")) {
            downloadDir = "apks";
            md5 = fileName.substring(fileName.lastIndexOf("_") + 1, fileName.lastIndexOf("."));
            fileName = fileName.replaceAll("_" + md5, "");
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".gif") || fileName.endsWith(".png")) {
            downloadDir = "img";
        } else if (fileName.endsWith(".so")) {
            downloadDir = "so";
        } else {
            resBo.setSuccess(false);
            resBo.setErrMsg("文件类型非法！仅支持上传apk格式的文件及jpg,gif,png格式图片文件！");
            logger.warn("文件类型非法！");
            ResponseUtil.printAjax(response, resBo);
            return;
        }
        Date date = new Date();
        String destDir = Constants.SOURCE_SITE_DIR + downloadDir + "/" + DateUtil.getFormatDate(date, "yyyyMMdd");
        File fileDir = new File(destDir);
        if (!fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        String destination = destDir + "/" + fileName;

        File file = new File(destination);

        logger.info("保存文件至save file to: " + destination);

        // 存储文件
        multipartFile.transferTo(file);

        // 下载路径
        String downloadUrl = "";
        if (fileName.endsWith(".apk")) {
            // 校验apk文件MD5值（必须）
            if (!md5.toLowerCase().equals(Md5Util.fileMD5(file).toLowerCase())) {
                resBo.setSuccess(false);
                resBo.setErrMsg("apk文件  【" + fileName + "】  MD5校验值不匹配，请检查MD5值！");
                logger.warn("apk文件  【" + fileName + "】  MD5校验值不匹配，请检查MD5值！");
                // 删除上传的文件
                file.delete();
                ResponseUtil.printAjax(response, resBo);
                return;
            }

            // 建立软连接（必须）
            File linkDir = new File(Constants.SOURCE_LINK_DIR);
            if (!linkDir.isDirectory()) {
                linkDir.mkdirs();
            }
            String path = Constants.SOURCE_LINK_DIR + fileName;
//            String[] rmCommand = {"rm", "-rf", path};
//            Runtime.getRuntime().exec(rmCommand);
            logger.info("apk文件  【" + fileName + "】开始执行建立软链接命令：ln -sf " + destination + " " + path + "");
            String[] linkCommand = {"/bin/ln", "-sf", destination, path};
            Runtime.getRuntime().exec(linkCommand);
            logger.info("apk文件  【" + fileName + "】执行建立软链接命令：执行完毕over");
            // 获取下载链接
            downloadUrl = Constants.S_DOWNLOAD_APK_URL + fileName;
        } else if (fileName.endsWith(".jpg") || fileName.endsWith(".gif") || fileName.endsWith(".png")) {
            downloadDir = "img";
            // 获取下载链接
            downloadUrl = Constants.S_DOWNLOAD_IMG_URL + downloadDir + "/" + DateUtil.getFormatDate(date, "yyyyMMdd") + "/" + fileName;
        } else if (fileName.endsWith(".so")) {
            // 建立软连接（必须）
            File linkDir = new File(Constants.SOURCE_LINK_DIR);
            if (!linkDir.isDirectory()) {
                linkDir.mkdirs();
            }
            String path = Constants.SOURCE_LINK_DIR + fileName;
//            String[] rmCommand = {"rm", "-rf", path};
//            Runtime.getRuntime().exec(rmCommand);
            logger.info("so文件  【" + fileName + "】开始执行建立软链接命令：ln -sf " + destination + " " + path + "");
            String[] linkCommand = {"/bin/ln", "-sf", destination, path};
            Runtime.getRuntime().exec(linkCommand);
            logger.info("so文件  【" + fileName + "】执行建立软链接命令：执行完毕over");
            // 获取下载链接
            downloadUrl = Constants.S_DOWNLOAD_APK_URL + fileName;
        }
        logger.info("成功返回下载地址return downloadUrl: " + downloadUrl);

        resBo.addResult("downloadUrl", downloadUrl);

        ResponseUtil.printAjax(response, resBo);
    }

}
